﻿using System;
using System.Linq;
using BaseRepository;
using BaseRepository.Elastic;
using Common;
using Elasticsearch.Net;
using Microsoft.Extensions.DependencyInjection;
using Nest;

namespace Extensions.Services;

public static class AddEs
{
    public static IServiceCollection AddEsSetup(this IServiceCollection service)
    {
        ArgumentNullException.ThrowIfNull(service);
        var options = Appsettings.app<EsOptions>("Startup", "Elasticsearch");
        if (options == null || options.Urls == null || options.Urls.Length==0)
        {
            throw new Exception("Elasticsearch 配置有误 请检查！");
        }

        if (!options.Enable)
        {
            Console.WriteLine("Elasticsearch 配置为enable false");
            return service;
        }

        ConnectionSettings settings;
        if (options.Urls.Length == 1)
        {
            settings = new ConnectionSettings(new Uri(options.Urls[0]));
        }
        else
        {
            settings = new ConnectionSettings(new StaticConnectionPool(options.Urls.Select(p => new Uri(p))));
        }

        var client = new ElasticClient(settings);
        // 单例注入封装好的es类
        service.AddSingleton(typeof(IElasticRepository),new ElasticRepository(client));

        return service;
    }
}


public class EsOptions
{
    public bool Enable { get; set; }
    public string[]? Urls { get; set; }
}